package com.example.nsddemo

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat

class MainActivity : AppCompatActivity() {

    companion object {
        private const val REQUEST_CODE_LOCATION = 1
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // 检查并请求位置权限 (API 23+)
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION),
                REQUEST_CODE_LOCATION
            )
        }

        val btnRegisterService = findViewById<Button>(R.id.btnRegister)
        val btnDiscoverServices = findViewById<Button>(R.id.btnDiscover)

        btnRegisterService.setOnClickListener {
            val intent = Intent(this, ServiceProviderActivity::class.java)
            startActivity(intent)
        }

        btnDiscoverServices.setOnClickListener {
            val intent = Intent(this, ServiceDiscoveryActivity::class.java)
            startActivity(intent)
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == REQUEST_CODE_LOCATION) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "位置权限已授予", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(this, "需要位置权限才能发现服务", Toast.LENGTH_LONG).show()
            }
        }
    }
}
